package com.example.simpletodolist;
import android.net.Uri;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.app.PendingIntent;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class SimpleToDoList extends ListActivity 
implements LoaderManager.LoaderCallbacks<Cursor> {

//	private ToDoListDatabase mDbHelper;
	static final int MENU_ADD = 0;
	static final int MENU_EDIT = 1;
	static final int LISTVIEW_VIEW = 3;

	private SimpleCursorAdapter adapter;
	
	private static final String[] COLUMN_NAMES = new String[]{
		ToDoListDatabase.KEY_ROWID,
		ToDoListDatabase.COL_TITLE,
		ToDoListDatabase.COL_BODY,
		ToDoListDatabase.COL_DATE, 
		ToDoListDatabase.COL_TIME
	};
	
	private static final int TODO_LIST_LOADER_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_to_do_list);
        
        String[] columnData = new String[] { ToDoListDatabase.COL_TITLE,ToDoListDatabase.COL_DATE };

		int[] viewIDs = new int[] { R.id.todoTitle,R.id.todoDate};
/*
 * setting cursor as null until actual cursor is received from loader manager
 * 
 */
		adapter = new SimpleCursorAdapter(this, R.layout.todo_item,
						null, columnData, viewIDs, 
						CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		
		// Associate the adapter with the ListView. 
		setListAdapter(adapter);
		
		// Initialize the Loader with id LOADER_ID, and this activity. 
		// As the Loader sees changes in the data, these changes will be 
		// reported back to this activity through the LoaderCallbacks interface
		LoaderManager loaderManager = getLoaderManager();
		loaderManager.initLoader(TODO_LIST_LOADER_ID, null, this);
       
        registerForContextMenu(getListView());
        
        setListAdapter(adapter);
        
        registerForContextMenu(getListView());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_simple_to_do_list, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_add:
        		createItem();
        		return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
//TODO cleanup this method if it goes unused
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {    		
    		super.onActivityResult(requestCode, resultCode, intent);
    		if (intent != null) {
    			/*
    			Bundle extras = intent.getExtras();
    			switch(requestCode) {
    			case MENU_EDIT:
    				setTextForResult(extras);
    				break;
    			}*/
    		}
    }

    protected void onListItemClick(ListView l, View v, int pos, long id) {
    	Intent intent = new Intent(this, ToDoItemView.class);
		Bundle bundle = createItemBundle(id);
		
		intent.putExtras(bundle);
		startActivityForResult(intent,LISTVIEW_VIEW);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_context_menu, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.menu_edit:
                editItem(info.id);
                return true;
            case R.id.menu_delete:
                deleteItem(info.id);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
    
    
    
    private void createItem() {
		Intent intent = new Intent(this, ToDoItemEdit.class);
		startActivityForResult(intent, MENU_ADD);
    }
    
    private void deleteItem(long id) {
    	Uri itemToDelete = Uri.withAppendedPath(ToDoListProvider.CONTENT_URI, 
    			String.valueOf(id));
    	//No direct reference to an instance of ToDoListProvider
    	getContentResolver().delete(itemToDelete, null, null);
    	removeItemFromAlarm(id);
    }
    
	private void removeItemFromAlarm(long id) {
		try {
			int rowId = (int) id;	// user would have many to-do's if this cast threw an exception
			Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
			
			PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), rowId, intent, 0);
			AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
			alarmManager.cancel(pendingIntent);
		} catch (Exception e) 
		{
			Log.d("on removeItemFromAlarm", e.getMessage());
		}
	}
    
    private void editItem(long id) {
		Intent intent = new Intent(this, ToDoItemEdit.class);
		Bundle bundle = createItemBundle(id);
		
		intent.putExtras(bundle);
		startActivityForResult(intent,MENU_EDIT);
    }

    private Bundle createItemBundle(long id) {
    	Bundle bundle = new Bundle();

    	Uri viewedToDoItem = Uri.withAppendedPath(
    			ToDoListProvider.CONTENT_URI, String.valueOf(id));
    	Cursor c = getContentResolver().query(
    			viewedToDoItem, COLUMN_NAMES, ToDoListDatabase.KEY_ROWID + "=" + id, 
    			null, null);
    	
    	if (c != null) {
    		while (c.moveToNext()) {
    			bundle.putString(ToDoListDatabase.COL_TITLE, 
    					c.getString(c.getColumnIndex(ToDoListDatabase.COL_TITLE)));
    			bundle.putString(ToDoListDatabase.COL_BODY, 
    					c.getString(c.getColumnIndex(ToDoListDatabase.COL_BODY)));
    			bundle.putString(ToDoListDatabase.COL_DATE, 
    					c.getString(c.getColumnIndex(ToDoListDatabase.COL_DATE)));
    			bundle.putString(ToDoListDatabase.COL_TIME,
    					c.getString(c.getColumnIndex(ToDoListDatabase.COL_TIME)));
    			bundle.putLong(ToDoListDatabase.KEY_ROWID, id);
    		}
    	}
		
		return bundle;
    }
    
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// We create the CursorLoader object here using the content URI. This 
		// loader object will pull columns based on the PROJECTION. 
		return new CursorLoader(this, ToDoListProvider.CONTENT_URI, 
				COLUMN_NAMES, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		adapter.swapCursor(arg1);	
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		adapter.swapCursor(null);
	}
}
